<?php
namespace app\home\controller;

use think\Controller;
use think\Request;
use app\common\model\Business\Business;
use app\common\model\Business\Source;
use app\common\model\Subject\Subject;
use app\common\model\Subject\Teacher\Teacher;
use app\common\model\Subject\Teacher\Follow;
use fast\Random;
use app\common\library\util\Token;
use app\common\library\util\Secure;
use app\common\controller\Home;
use app\common\model\Live\Live;
use app\common\model\Live\Product as LiveProduct;
use app\common\model\Product\Product;
use app\common\model\Subject\Comment;
use think\Cookie;
use think\model\Collection;

class Index extends Home
{
    public function __construct(Request $request)
    {
        $this->noLogin = ['*'];
        parent::__construct($request);
    }
    public function index()
    {   
        $subjectSwiper = Subject::where('id','in',Subject::field('MAX(id) as max_id')->group('cateid')->select()->column('max_id'))
                        ->limit(6)->select()->toArray();
        // halt($subjectSwiper);
        $this->assign('subjectSwiper',$subjectSwiper);
        $subject = Subject::select()->sort(function ($a, $b) {
            return -($a['likes_num'] <=> $b['likes_num']);
        });
        $maxDisplay = 10;
        $subjectDisplay = $subject->slice(0,$subject->count()<$maxDisplay?$subject->count():$maxDisplay)
                        ->toArray();
        $this->assign('subjectList',$subjectDisplay);
        
        $teacher = Teacher::select()->sort(function ($a, $b) {
            return -(count($a['follows']) <=> count($b['follows']));
        });
        // halt($teacher->toArray());
        $maxDisplay = 6;
        $teacherDisplay = $teacher->slice(0,$teacher->count()<$maxDisplay?$teacher->count():$maxDisplay)
                        ->toArray();
        $this->assign('teacherList',$teacherDisplay);
        return $this->view->fetch();
    }
    public function login(Request $request)
    {
        Cookie::set('token',null);
        $mobileParent = null;
        if($request->param('token')){
            $mobileParent = Secure::decrypt($request->param('token'));
        }
        if($request->isGet())
        {
            return $this->fetch();
        }
        $mobile = $request->post("mobile","","trim");
        $passwordInput = $request->post("password","","trim");
        $business = Business::where('mobile',$mobile)->select();
        if(!$business->isEmpty()){
            $password = $business[0]["password"];
            $salt = $business[0]["salt"];
            if(md5(md5($passwordInput) . $salt)==$password){
                $token = Token::generateToken([
                    "id" => $business[0]["id"],
                    "mobile" => $mobile,
                ]);
                Cookie::set('token',$token);
                $this->success("登录成功","/");
                exit;
                // halt($token);
            }else{
                $this->error("用户名或密码错误","/home/index/login");
                exit;
            }
        }else{
            $nickname = substr($mobile,0,3).'****'.substr($mobile,strlen($mobile)-4,strlen($mobile));
            $salt = Random::alnum(10);
            $password = md5(md5($passwordInput) . $salt);
            $sourceid = Source::whereLike('name','%云课堂%')->find()['id'];
            $data = [
                'mobile' => $mobile,
                'nickname' => $mobile,
                'password' => $passwordInput,
                'salt' => $salt,
                'gender' => 0,
                'sourceid' => $sourceid,
                'deal' => 0,
                'money' => 0,
                'auth' => 0,
            ];
            if($mobileParent){
                $parent = Business::where('mobile',$mobileParent)->find();
                if($parent){
                    $data['parentid'] = $parent['id'];
                }
            }
            $result = $this->validate($data,"app\\common\\validate\\Business\\Business");
            if(true !== $result){
                // 验证失败 输出错误信息
                $this->error($result,"/home/index/login");
            }
            $data['nickname'] = $nickname;
            $data['password'] = $password;
            $business = Business::create($data);
            $business->save();
            if(!$business['id']){
                $this->error("注册失败","/home/index/login");
            }
            $token = Token::generateToken([
                "id" => $business["id"],
                "mobile" => $mobile,
            ]);
            Cookie::set('token',$token);
            $this->success("注册成功","/");
        }
        
    }
    public function logout()
    {
        Cookie::set('token',null);
        $this->redirect('/home/index/login');
    }
    public function ranking()
    {
        $maxDisplay = 10;
        $subject = Subject::select()->sort(function ($a, $b) {
            return -($a['orders_num'] <=> $b['orders_num']);
        });
        $subjectList = $subject->slice(0,$subject->count()<$maxDisplay?$subject->count():$maxDisplay)->toArray();
        // halt($subjectList[0]['orders']);
        $this->assign('subjectList',$subjectList);
        return $this->fetch();
    }
    public function comment()
    {
        $commentList = Comment::where('id','in',Comment::field('MAX(id) as max_id')->group('subid')->select()->column('max_id'))
                        ->limit(6)->select()->toArray();
        // halt($commentList);
        $this->assign('commentList',$commentList);
        return $this->fetch('comment_list');
    }
    public function subject()
    {
        return $this->fetch();
    }
    public function live()
    {
        $liveModel = new Live();
        $productModel = new Product();
        $liveProductModel = new LiveProduct();
        $count = $liveModel->count();
        $live = $liveModel->limit(random_int(0,$count),1)->find();
        $liveProduct = $liveProductModel->where(['liveid'=>$live['id'],'type'=>'subject'])->select();
        $this->assign('liveProduct',$liveProduct);
        return $this->fetch();
    }
}
